import sys
import asyncio
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QVBoxLayout, QWidget
from PyQt5.QtCore import QTimer
import aiofile  # 需提前安装：pip install aiofile
from asyncqt import QEventLoop  # 用于桥接 asyncio 和 PyQt5 事件循环

class AsyncFileWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("异步文件读写示例")
        self.resize(400, 200)
        
        # UI 组件
        self.status_label = QLabel("准备就绪", self)
        self.progress_label = QLabel("进度：0%", self)
        self.start_button = QPushButton("开始读写")
        self.start_button.clicked.connect(self.start_async_io)
        
        # 布局
        layout = QVBoxLayout()
        layout.addWidget(self.status_label)
        layout.addWidget(self.progress_label)
        layout.addWidget(self.start_button)
        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)
    
    async def read_file_async(self, filename):
        """异步读取文件内容"""
        async with aiofile.open(filename, 'r') as afp:
            content = await afp.read()
            return content
    
    async def write_file_async(self, filename, content):
        """异步写入文件内容"""
        async with aiofile.open(filename, 'w') as afp:
            await afp.write(content)
    
    async def perform_io_tasks(self):
        """执行异步读写任务"""
        try:
            # 模拟同时读写操作
            read_task = asyncio.create_task(self.read_file_async("input.txt"))
            write_task = asyncio.create_task(self.write_file_async("output.txt", "异步写入的内容"))
            
            # 等待所有任务完成
            await asyncio.gather(read_task, write_task)
            
            # 更新 UI（需在主线程执行）
            self.status_label.setText("任务完成")
            self.progress_label.setText("进度：100%")
        except Exception as e:
            self.status_label.setText(f"错误：{str(e)}")
    
    def start_async_io(self):
        """启动异步任务"""
        self.start_button.setEnabled(False)
        self.status_label.setText("正在执行...")
        
        # 使用 QTimer 触发异步任务（避免阻塞 GUI 线程）
        QTimer.singleShot(0, lambda: asyncio.ensure_future(self.perform_io_tasks()))

if __name__ == "__main__":
    app = QApplication(sys.argv)
    loop = QEventLoop(app)  # 创建 asyncio 兼容的事件循环
    asyncio.set_event_loop(loop)
    
    window = AsyncFileWindow()
    window.show()
    
    with loop:  # 启动事件循环
        sys.exit(loop.run_forever())